# from paho import mqtt
import paho.mqtt.client as mqtt

class MqttCallback:
    def on_connect(self, client, userdata, flags, rc):
        pass

    def on_message(self, client, userdata, msg):
        pass

# 发布器
class MqttPublisher:
    def __init__(self, broker_address, broker_port=1883, client_id=None):
        self.broker_address = broker_address
        self.broker_port = broker_port
        self.client = mqtt.Client(client_id=client_id)

    def connect(self):
        self.client.connect(self.broker_address, self.broker_port)
        print("Publisher connected to MQTT Broker")

    def publish(self, topic, message):
        self.client.publish(topic, message)
        print(f"Published message to topic {topic}")

    def disconnect(self):
        self.client.disconnect()
        print("Publisher disconnected")

# 订阅器
class MqttSubscriber:
    def __init__(self, broker_address, broker_port=1883, client_id=None, callback: MqttCallback = None):
        self.broker_address = broker_address
        self.broker_port = broker_port
        self.client = mqtt.Client(client_id=client_id)
        self.callback = callback if callback else MqttCallback()
        self.client.on_connect = self.callback.on_connect
        self.client.on_message = self.callback.on_message

    def connect(self):
        self.client.connect(self.broker_address, self.broker_port)
        print("Subscriber connected to MQTT Broker")

    def loop_start(self):
        self.client.loop_start()

    def loop_stop(self):
        self.client.loop_stop()

    def subscribe(self, topic):
        self.client.subscribe(topic)
        print(f"Subscribed to topic {topic}")

    def disconnect(self):
        self.client.disconnect()
        print("Subscriber disconnected")
